/*
 * ml20gui - The MSN Webcam Recorder
 * This source code is under the GNU Public License (GPL).
 * Written by Ramiro Polla
 * Initial release: june 3rd, 2005
 *
 * this program records MSN Webcam Video
 */

#include "ml20gui.h"

extern char folder[MAX_PATH];

FILE *open_file( stream_t *stream )
{
    char fullname[MAX_PATH];

    get_fullname( stream->fname, fullname );

    stream->fp = fopen( fullname, "wb" );

    return stream->fp;
}

void close_file(stream_t *stream)
{
    if (stream->fp) {
        fclose(stream->fp);
        stream->fp = NULL;
    }
}

void get_fullname( char *inname, char *outname )
{
    sprintf( outname, "%s%s", folder, inname );
}

char *build_streamname( stream_t *stream )
{
    invite_t *invite;
    char *fname = malloc( MAX_PATH );
    char src[MAX_PATH];
    char dst[MAX_PATH];
    char fullname[MAX_PATH];
    struct _stat sta;
    int i = 0;

    if( (invite = find_invite_ip( stream->flow, TYPE_SRC )) )
        sprintf( src, "%s", invite->name );
    else
        sprintf( src, "%d.%d.%d.%d.%d",
        (uint8_t) ((stream->flow->src & 0xff000000) >> 24),
        (uint8_t) ((stream->flow->src & 0x00ff0000) >> 16),
        (uint8_t) ((stream->flow->src & 0x0000ff00) >> 8),
        (uint8_t) ((stream->flow->src & 0x000000ff)),
        stream->flow->sport
        );

    if( (invite = find_invite_ip( stream->flow, TYPE_DST )) )
        sprintf( dst, "%s", invite->name );
    else
        sprintf( dst, "%d.%d.%d.%d.%d",
        (uint8_t) ((stream->flow->dst & 0xff000000) >> 24),
        (uint8_t) ((stream->flow->dst & 0x00ff0000) >> 16),
        (uint8_t) ((stream->flow->dst & 0x0000ff00) >> 8),
        (uint8_t) ((stream->flow->dst & 0x000000ff)),
        stream->flow->dport
        );

    do {
        char istring[8];
        const char *ext = flags_extension( stream->flags );

        sprintf( istring, " (%d)", i );

        sprintf( fname,
            "%s %s %s%s.%s",
            src,
            str_to,
            dst,
            i ? istring : "",
            ext
            );
        get_fullname( fname, fullname );

        i++;
    }
    while( _stat( fullname, &sta ) != -1 );

    return fname;
}

const char *flags_extension( int flags )
{
    if( IS_SET( flags, FLOW_VC ) )
        return "vc";
    else if( IS_SET( flags, FLOW_UDP ) )
        return "udp";
    else
        return "ml20";
}

int extension_flags( const char *extension )
{
    int size;
    if( !extension )
        return 0;
    size = strlen( extension );
    if(      size > 2 && !memcmp( extension+size-2, "vc", 2 ) )
        return FLOW_VC;
    else if( size > 2 && !memcmp( extension+size-3, "udp", 3 ) )
        return FLOW_UDP;
    else if( size > 2 && !memcmp( extension+size-4, "ml20", 4 ) )
        return FLOW_ML20;
    return 0;
}
